const fs = require('fs'),
  command = require('./command')

const suffixList = ['.js', '.vue', '.jsx', '.ts', '.html']
// regex = new RegExp(/debugger|window.alert|alert|console.log/g)

let excludes = require(`${process.cwd()}/package.json`)['husky-excludes'] || []
excludes = excludes.map(exclude => new RegExp(exclude))
const _excludes = ['.eslint', 'babel.config.js', 'jsconfig.js', 'dist', 'assets', 'static', 'iconfont']

console.log('')
console.log('=========================================')
console.log('正在校验非法关键字')

let fileNames = []

command.exec('git diff --name-only --cached').then(buffer => {
  buffer && buffer.split('\n').map(fileName => {
    if (fileName.endsWith('package.json')) {
      const packages = require(`${process.cwd()}/${fileName}`)
      if (!fs.existsSync(`${process.cwd()}/.package.git`)) {
        console.log('package.json 禁止提交')
        console.log('=========================================')
        process.exit(1)
      }
      if (Object.keys(packages.dependencies).find(dependence => packages.dependencies[dependence].includes('file:'))) {
        console.log('package.json 中含有本地依赖项, 禁止提交')
        console.log('=========================================')
        process.exit(1)
      }
      return
    }
    if (fileName.startsWith('.env')) {
      if (!fs.existsSync(`${process.cwd()}/.env.git`)) {
        console.log('环境变量配置文件不能随意改动, 禁止提交')
        console.log('=========================================')
        process.exit(1)
      }
      return
    }
    if (!fs.existsSync(fileName)) {
      return
    }
    if (excludes.find(exclude => exclude.test(fileName))) {
      // 排除忽略文件
      return
    }
    if (_excludes.find(exclude => fileName.includes(exclude))) {
      return
    }
    if (!suffixList.find(suffix => fileName.endsWith(suffix))) {
      return
    }
    const content = fs.readFileSync(fileName, 'utf8')
      .replace(/\$alert/g, '')
      .replace(/alert\s+\(/g, 'alert(')
    if (content.includes('debugger') ||
      content.includes('window.alert') ||
      content.includes('alert(') ||
      content.includes('console.log') ||
      (content.includes('true#') && fileName.indexOf('mock/modules/') != -1)
    ) {
      fileNames.push(fileName)
    }
  })
  if (fileNames.length == 0) {
    console.log('校验通过')
    fs.existsSync(`${process.cwd()}/.package.git`) && fs.unlinkSync(`${process.cwd()}/.package.git`)
    fs.existsSync(`${process.cwd()}/.env.git`) && fs.unlinkSync(`${process.cwd()}/.env.git`)
  } else {
    console.log(fileNames.join('\n'))
    console.log('以上文件中含有 debugger 或 console.log 或 alert 或 mock 模拟数据被开启, 禁止提交')
  }
  console.log('=========================================')
  fileNames.length > 0 && process.exit(1)
})
